<?php

namespace App\Http\Controllers\V1\BasicData;

use App\Http\Requests\V1\CollectorRequest;
use App\Models\V1\BasicCollectors;
use App\Models\V1\BasicTransformers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Log;

class CollectorsController extends Controller
{
    /**
     * 显示变压器数据管理页面
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('v1.collectors');
    }

    /**
     * 获取变压器数据
     *
     * @param Request $request
     */
    public function postIndex(Request $request)
    {
        $response = [
            'code' => 1,
            'msg' => '',
            'count' => 0,
            'data' => [],
        ];

        // 获取符合查询条件的变压器数据
        $currentPage = $request->get('page');
        $rows = $request->get('limit');
        $keywords = $request->get('keywords');

        // 获取符合查询条件的变压器数据
        $data = $this->getCollectorsList($currentPage, $rows, $keywords);

        if (!$data->isEmpty()) {

            $formatList = array();

            $count = $data->total() > 0 ? $data->total() : 0;

            if ($count > 0) {
                // 格式化数据
                foreach ($data->items() as $item) {
                    $transformerObj = $item->transformer;
                    $formatItem['code'] = $item['code'];
                    $formatItem['mac_code'] = $item['mac_code'];
                    $formatItem['transformer_code'] = $transformerObj['model_code'];
                    $formatItem['model'] = $item['model'];
                    $formatItem['updated_at'] = $item['updated_at']->format('Y-m-d H:i:s');
                    $formatItem['created_at'] = $item['created_at']->format('Y-m-d H:i:s');
                    array_push($formatList, $formatItem);
                }

                $response['code'] = 0;
                $response['msg'] = '加载数据成功';
                $response['count'] = $count;
                $response['data'] = $formatList;
            }
        }

        return $response;
    }

    /**
     * 进入单条收集器数据显示界面（(适用于新增addData、查看viewData、编辑editData功能）
     *
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function showView(Request $request)
    {
        $data['view'] = $request->input('view');
        switch ($request->input('view')){
            case 'addData':
                $data['randomCode'] = 'CTR' . uniqid();
                $data['transformers'] = $this->getTransformersList();
                return view('v1.form.collector_item', $data);
                break;
            case 'editData':
                $data['code'] = $request->input('code');
                $collector = $this->getCollectorByCode($data['code']);
                $data['transformers'] = $this->getTransformersList();
                $data['itemData'] = $collector;
                return view('v1.form.collector_item', $data);
                break;
            case 'viewData':
                $data['code'] = $request->input('code');
                $collector = $this->getCollectorByCode($data['code']);
                $data['itemData'] = $collector;
                return view('v1.form.collector_item', $data);
                break;

        }
    }

//    /**
//     * 显示收集器数据导入页面
//     *
//     * @param Request $request
//     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
//     */
//    public function importView(Request $request)
//    {
//        // 获取登录用户
//        $loginUser = Auth::user();
//
//        $data['view'] = $request->input('view');
//        $data['code'] = $loginUser->getAttribute('code');
//
//        return view('v1.form.upload_excel', $data);
//    }

    /**
     * 更新收集器基本信息(单元格)
     *
     * @param CollectorRequest $request
     * @return array
     */
    public function updateCellData(CollectorRequest $request)
    {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '收集器代码[' . $request->input('code') . '],更新失败！',
        ];

        if ($request->method() === 'POST') {
            // 验证请求
            $this->validateCollector($request);

            // 更新收集器信息
            $successFlag = $this->handleUpdate($request, true);

            if ($successFlag) {
                $response['rspStatus'] = true;
                $response['rspMsg'] = '收集器代码[' . $request->input('code') . '],更新成功！';
            }
        }

        return $response;
    }

    /**
     * 更新收集器基本信息
     *
     * @param CollectorRequest $request
     * @return array
     */
    public function updateData(CollectorRequest $request)
    {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '收集器代码[' . $request->input('code') . '],更新失败！',
        ];

        if ($request->method() === 'POST') {
            // 验证请求
            $this->validateCollector($request);

            // 更新收集器信息
            $successFlag = $this->handleUpdate($request, false);

            if ($successFlag) {
                $response['rspStatus'] = true;
                $response['rspMsg'] = '收集器代码[' . $request->input('code') . '],更新成功！';
            }
        }

        return $response;
    }

    /**
     * 新增基本信息
     *
     * @param Request $request
     * @return array
     */
    public function addData(Request $request)
    {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '采集器[' . $request->input('code') . '],新增失败！',
        ];

        if ($request->method() === 'POST') {
            // 验证请求
            $rules['code'] = 'bail|required';
            $rules['mac_code'] = 'bail|required';
            $rules['transformer_code'] = 'bail|required|exists:basic_transformers,code,deleted_at,NULL';
//            $rules['captcha'] = 'bail|required|captcha';
            $messages['code.required'] = '采集器代码不能为空';
            $messages['mac_code.required'] = '采集器编码不能为空';
            $messages['transformer_code.required'] = '变压器代码不能为空';
            $messages['transformer_code.exists'] = '变压器代码不存在';
//            $messages['captcha.required'] = '验证码不能为空';
//            $messages['captcha.captcha'] = '验证码错误';
            $this->validate($request, $rules, $messages);

            // 新增信息
            $successFlag = $this->handleAdd($request);

            if ($successFlag) {
                $response['rspStatus'] = true;
                $response['rspMsg'] = '采集器[' . $request->input('code') . '],新增成功！';
            }
        }

        return $response;
    }

    /**
     * 删除收集器基本信息
     *
     * @param CollectorRequest $request
     * @return array
     */
    public function deleteData(CollectorRequest $request)
    {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '收集器代码[' . $request->input('code') . '],删除失败！',
        ];

        if ($request->method() === 'POST') {
            // 验证请求
            $this->validateCollector($request);

            // 删除收集器信息
            $successFlag = $this->handleDelete($request, false);

            if ($successFlag) {
                $response['rspStatus'] = true;
                $response['rspMsg'] = '收集器代码[' . $request->input('code') . '],删除成功！';
            }
        }

        return $response;
    }

    /**
     * 批量删除收集器基本信息
     *
     * @param CollectorRequest $request
     * @return array
     */
    public function deleteBatchData(CollectorRequest $request)
    {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '收集器批量删除失败！',
        ];

        if ($request->method() === 'POST') {

            // 删除收集器信息
            $successFlag = $this->handleDelete($request, true);

            if ($successFlag) {
                $response['rspStatus'] = true;
                $response['rspMsg'] = '收集器批量删除成功！';
            }
        }

        return $response;
    }

    ///////////////////////////////////////////////////////////////////
    /// 获取数据功能函数
    ///////////////////////////////////////////////////////////////////
    /**
     * 分页查询符合条件的收集器列表数据
     *
     * @param int $page 当前页数
     * @param $rows 每页显示条数
     * @param $keywords 搜索关键词
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator 分页对象
     */
    private function getCollectorsList($page = 1, $rows, $keywords)
    {
        if (!isset($keywords) || empty($keywords)) {
            $data = BasicCollectors::orderBy('created_at', 'asc')->paginate($rows, ['*'], 'page', $page);
        } else {
            $data = BasicCollectors::where('name', 'like', '%' . $keywords . '%')->orderBy('created_at', 'asc')
                ->paginate($rows, ['*'], 'page', $page);
        }
        return $data;
    }

    /**
     * 根据收集器代码获取对应教职工信息
     *
     * @param $code
     * @return \Illuminate\Database\Eloquent\Model|null|static
     */
    private function getCollectorByCode($code)
    {
        $collector = BasicCollectors::where('code', $code)->first();
        $transformer = $collector->transformer;
        $collector['transformer_code'] = $transformer['model_code'];
        return $collector;
    }

    /**
     * 获取所有的变压器列表信息
     *
     * @param $code
     * @return \Illuminate\Database\Eloquent\Model|null|static
     */
    private function getTransformersList()
    {
        $data = BasicTransformers::get(['code', 'model_code']);
        return $data;
    }

    /**
     * 格式化采集器状态
     *
     * @param $val
     * @return string
     */
    private function formateStateData($val)
    {
        $strFormat = '<span class="layui-bg-cyan">未知</span>';
        switch ($val) {
            case 0:
                $strFormat = '<span class="layui-bg-red">异常</span>';
                break;
            case 1:
                $strFormat = '<span class="layui-bg-green">正常</span>';
                break;
        }
        return $strFormat;
    }

    ///////////////////////////////////////////////////////////////////
    /// 验证表单请求功能函数
    ///////////////////////////////////////////////////////////////////
    /**
     * 处理新增、更新收集器信息验证请求
     *
     * @param Request $request
     */
    private function validateCollector(Request $request)
    {
        $rules = $request->rules();
        if ($request->input("captcha") !== null) {
            $rules['captcha'] = 'bail|required|captcha';
        }
        $messages = $request->messages();
        // 执行表单数据验证
        $this->validate($request, $rules, $messages);
    }

    ///////////////////////////////////////////////////////////////////
    /// 业务逻辑功能函数
    ///////////////////////////////////////////////////////////////////
    /**
     * 处理更新收集器信息
     *
     * @param Request $request
     * @param bool $bCell 是否为单元格修改数据
     * @return bool
     */
    private function handleUpdate(Request $request, $bCell)
    {
        $where = $request->input('code');

        if ($bCell) { // 单元格修改
            $attrs = $request->input('attrs');
            $values = $request->input('values');
            // 拼装更新数据数组
            $updateData = array();
            $counter = 0;
            foreach ($attrs as $attr) {
                $updateData[$attr] = $values[$counter];
                $counter++;
            }
        } else { // 表单修改
            // 拼装更新数据数组
            $updateData = [
                'mac_code' => $request->input('mac_code'),
                'transformer_code' => $request->input('transformer_code'),
                'state' => $request->input('state'),
            ];

            if ($request->input('model') !== "") {
                $updateData['model'] = $request->input('model');
            }
        }

        $rspObj = BasicCollectors::where('code', $where)
            ->update($updateData);

        return $rspObj;
    }

    /**
     * 处理更新收集器信息
     *
     * @param Request $request
     * @param bool $bBatch 是否为批量数据
     * @return bool
     */
    private function handleDelete(Request $request, $bBatch)
    {
        $where = $request->input('code');

        if ($bBatch) { // 批量删除
            $codeList = $request->input('code');

            foreach ($codeList as $code) {
                $rspObj = BasicCollectors::where('code', $code)->delete();
            }
        } else { // 单条删除
            $rspObj = BasicCollectors::where('code', $where)
                ->delete();
        }

        return $rspObj;
    }

    /**
     * 处理新增信息
     *
     * @param Request $request
     * @return bool
     */
    private function handleAdd(Request $request)
    {
        // 拼装新增数据数组
        $insertData = [
            'code' => $request->input('code'),
            'mac_code' => $request->input('mac_code'),
            'transformer_code' => $request->input('transformer_code'),
            'model' => isset($request['model']) ? $request->input('model') : NULL,
        ];

        $rspObj = BasicCollectors::create($insertData);

        return $rspObj;
    }
}
